<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="老人姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="床位号" prop="bedNo">
        <el-input
          v-model="queryParams.bedNo"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="overdueList">
      <el-table-column label="序号" align="center" prop="id" width="80" />
      <el-table-column label="老人姓名" align="center" prop="elderlyName" />
      <el-table-column label="床位号" align="center" prop="bedNo" />
      <el-table-column label="欠款金额（元）" align="center" prop="overdueAmount">
        <template #default="scope">
          <span style="color: #f56c6c; font-weight: bold;">{{ scope.row.overdueAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付截止时间" align="center" prop="paymentDeadline" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.paymentDeadline, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120">
        <template #default="scope">
          <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script setup name="OverdueElderly">
import { listBill } from "@/api/system/bill"

const { proxy } = getCurrentInstance()

const overdueList = ref([])
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  name: null,
  bedNo: null
})

/** 查询欠费老人列表 */
function getList() {
  loading.value = true
  
  // 查询所有账单
  listBill(queryParams.value).then(response => {
    const allBills = response.rows || []
    const currentTime = new Date().getTime()
    const currentDate = new Date()
    
    console.log('=== 开始筛选欠费老人 ===')
    console.log('当前时间:', currentDate.toLocaleString())
    console.log('当前时间戳:', currentTime)
    console.log('总账单数:', allBills.length)
    
    // 过滤出欠费的账单（支付截止时间已过期 AND 交易状态为待支付）
    const overdueBills = allBills.filter(bill => {
      // 检查必要字段
      if (!bill.paymentDeadline || !bill.transactionStatus) {
        console.log('账单ID:', bill.id, '- 缺少必要字段，跳过')
        return false
      }
      
      // 解析支付截止时间
      const deadlineDate = new Date(bill.paymentDeadline)
      const deadlineTime = deadlineDate.getTime()
      
      // 检查时间是否有效
      if (isNaN(deadlineTime)) {
        console.log('账单ID:', bill.id, '- 支付截止时间格式错误，跳过')
        return false
      }
      
      // 判断是否过期（支付截止时间 < 当前时间）
      const isOverdue = deadlineTime < currentTime
      
      // 判断是否待支付
      const isPending = bill.transactionStatus === '待支付'
      
      console.log('=== 账单筛选检查 ===')
      console.log('账单ID:', bill.id)
      console.log('老人姓名:', bill.elderly?.name || bill.name || '未知')
      console.log('支付截止时间:', bill.paymentDeadline)
      console.log('截止时间对象:', deadlineDate.toLocaleString())
      console.log('截止时间戳:', deadlineTime)
      console.log('当前时间戳:', currentTime)
      console.log('时间差(小时):', (currentTime - deadlineTime) / (1000 * 60 * 60))
      console.log('是否过期:', isOverdue)
      console.log('交易状态:', bill.transactionStatus)
      console.log('是否待支付:', isPending)
      console.log('是否显示:', isOverdue && isPending)
      console.log('---')
      
      // 支付截止时间已过期 AND 交易状态为待支付
      return isOverdue && isPending
    })
    
    console.log('=== 筛选结果 ===')
    console.log('符合条件的欠费账单数:', overdueBills.length)
    console.log('筛选出的账单ID列表:', overdueBills.map(bill => bill.id))
    
    // 构建欠费老人数据
    overdueList.value = overdueBills.map(bill => {
      console.log('=== 处理账单数据 ===')
      console.log('账单ID:', bill.id)
      console.log('老人姓名:', bill.elderly?.name || bill.name)
      console.log('elderly对象:', bill.elderly)
      console.log('bed对象:', bill.bed)
      console.log('elderly.bed:', bill.elderly?.bed)
      console.log('床位号映射结果:', bill.elderly?.bed?.bedNo || bill.bed?.bedNo || bill.bedNo || '')
      console.log('完整bill对象:', bill)
      
      return {
        id: bill.id,
        elderlyName: bill.elderly?.name || bill.name || '',
        bedNo: bill.elderly?.bed?.bedNo || bill.bed?.bedNo || bill.bedNo || '',
        overdueAmount: bill.payableAmount || 0, // 欠款金额 = 应付金额
        paymentDeadline: bill.paymentDeadline,
        billId: bill.id,
        elderlyId: bill.elderlyId
      }
    })
    
    total.value = overdueList.value.length
    loading.value = false
    
    console.log('欠费老人数据:', overdueList.value)
  }).catch(error => {
    console.error('查询失败:', error)
    loading.value = false
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 查看详情 */
function handleView(row) {
  // 这里可以跳转到账单详情页面
  console.log('查看详情:', row)
  proxy.$router.push('/system/bill/detail?id=' + row.billId)
}

// 初始化加载数据
getList()
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>

